package me.muci.B_netty.NIO;

import org.junit.Test;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * ClassName: BasicChannel
 * <p>
 * Description:
 * <p>
 * date: 2021/8/20 9:37
 *
 * @author muci
 * @since JDK 1.8
 */
public class BasicChannel {

    /**
     * 文件copy第一次方式
     * @throws IOException
     */
    @Test
    public void fileChannelTest() throws IOException {
        FileInputStream fis = new FileInputStream("src\\main\\resources\\NIO\\fileChannel\\read.txt");
        FileOutputStream fos = new FileOutputStream("src\\main\\resources\\NIO\\fileChannel\\writer.txt");

        FileChannel fosChannel = fos.getChannel();
        FileChannel fisChannel = fis.getChannel();

        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

        int read = fisChannel.read(byteBuffer);
        while (read != -1){
            byteBuffer.flip();
            fosChannel.write(byteBuffer);
            byteBuffer.clear();
            read = fisChannel.read(byteBuffer);
        }
        fis.close();
        fos.close();
    }

    /**
     * 文件copy第二种方式
     * @throws IOException
     */
    @Test
    public void fileChannelCopy2Test() throws IOException {
        FileInputStream fis = new FileInputStream("src\\main\\resources\\NIO\\fileChannel\\image.jpg");
        FileOutputStream fos = new FileOutputStream("src\\main\\resources\\NIO\\fileChannel\\image_copy.jpg");

        FileChannel fisChannel = fis.getChannel();
        FileChannel fosChannel = fos.getChannel();

        fosChannel.transferFrom(fisChannel,0,fisChannel.size());
//        fisChannel.transferTo(0,fosChannel.size(),fosChannel);

        fis.close();
        fos.close();
    }
    public static void main(String[] args) throws IOException {
        RandomAccessFile aFile = new RandomAccessFile("src\\main\\resources\\NIO\\basicChannle.txt","rw");
        FileChannel channel = aFile.getChannel();
        ByteBuffer buffer = ByteBuffer.allocate(115);
        int read = channel.read(buffer);

        while (read != -1){
            System.out.println("read = " + read);
            buffer.flip();
            System.out.print(new String(buffer.array()));
            buffer.clear();
            read = channel.read(buffer);
        }
        aFile.close();
    }
}
